package com.hmdp.service.impl;

import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import com.hmdp.utils.HmdpException;
import com.hmdp.utils.RedisConstant;
import com.hmdp.utils.ResultCodeEnum;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.StringJoiner;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {
    @Autowired
    private IUserService userServiceImpl;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Blog queryBlogById(Long id) {
        Blog blog = getById(id);
        if (blog == null) {
            throw new HmdpException(ResultCodeEnum.DATA_ERROR);
        }
        Long userId = blog.getUserId();
        User user = userServiceImpl.getById(userId);
        blog.setIcon(user.getIcon());
        blog.setName(user.getNickName());
        isBlogLike(blog);
        return blog;
    }

    @Override
    public List<UserDTO> queryBlogLikes(Integer id) {
        String key = RedisConstant.Blog_liked + id;
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(key, 0, 5);
        List<UserDTO> collect = new ArrayList<>();
        if (top5.isEmpty() || top5 == null) {
            return collect;
        }

        List<Long> ids = top5.stream().map(Long::valueOf).collect(Collectors.toList());
        List<User> users = userServiceImpl.listByIds(ids);
        collect = users.stream().map(item -> {
            UserDTO userDTO = new UserDTO();
            BeanUtils.copyProperties(item, userDTO);
            return userDTO;
        }).collect(Collectors.toList());
        return collect;
    }

    @Override
    public ScrollResult queryBlogOfFollow(Long max, Integer offset) {
//        1.获得当前的收件箱。
        Long userId = UserHolder.getUser().getId();
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet().reverseRangeByScoreWithScores(RedisConstant.Free + userId, 0, max, offset, 2);
        if (typedTuples == null || typedTuples.isEmpty()) {
            throw new HmdpException(ResultCodeEnum.DATA_Not);
        }

//        2.  offset （最小的是多少个。）    max是一个时间戳。
        ArrayList<Long> blog_ids = new ArrayList<>(typedTuples.size());
        long time = 0;
        int offsetCount = 1;
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
//            值
            String value = typedTuple.getValue();
//分数
//5 4 4 2 2

            if (time == typedTuple.getScore().longValue()) {
                offsetCount++;
            } else {
                time = typedTuple.getScore().longValue();
                offsetCount = 1;
            }
            blog_ids.add(Long.valueOf(value));
        }

//      3.  根据获得的数据拿到所有文章，之后拿到最小的时间戳  还有最小个数

//ORDER BY FIELD(id, 3, 1, 2);
        StringJoiner joiner = new StringJoiner(",");
        for (Long id : blog_ids) {
            joiner.add(String.valueOf(id)); // 将 Long 类型转为 String
        }

        String result = joiner.toString();
        List<Blog> blogs = query().in("id", blog_ids).last("ORDER BY FIELD(id," + result + ")").list();


        for (Blog blog : blogs) {
            User user = userServiceImpl.getById(userId);
            blog.setIcon(user.getIcon());
            blog.setName(user.getNickName());
            isBlogLike(blog);
        }

        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogs);
        scrollResult.setOffset(offsetCount);
        scrollResult.setMinTime(time);


        return scrollResult;
    }


    public void isBlogLike(Blog blog) {
        String blogLiked_key = RedisConstant.Blog_liked + blog.getId();
        Double score = stringRedisTemplate.opsForZSet().score(blogLiked_key, UserHolder.getUser().getId().toString());
        blog.setIsLike(score != null);
    }
}
